package com.moyun.finance.service;

import com.moyun.finance.entity.AllType;
import com.moyun.finance.entity.Response;
import com.moyun.finance.repository.AllTypeRepository;
import com.moyun.finance.utils.BaseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AllTypeService {
    @Autowired
    AllTypeRepository ar;

    public Response save(AllType allType){
        allType.setId(BaseUtil.uuid());
        ar.save(allType);
        return new Response("添加成功!",true);
    }

    public Response update(AllType allType){
        ar.save(allType);
        return new Response("修改成功!",true);
    }

    public Response delete(AllType allType){
        ar.delete(allType);
        return new Response("删除成功",true);
    }

    public AllType findOneById(String allTypeId){
        return ar.findById(allTypeId).orElse(null);
    }

    //本公司所有
    public List<AllType> findTree(String companyId, int type){
        List<AllType> allMenus =  ar.findByCompanyIdAndType(companyId, type);
        List<AllType> rootMenu = new ArrayList<>();
        for(AllType tm : allMenus){
            if("0".equals(tm.getParentId())){
                rootMenu.add(tm);
            }
        }
        for(AllType tm : rootMenu){
            /* 获取根节点下的所有子节点 使用getChild方法*/
            List<AllType> childList = getChild(tm.getId(), allMenus);
            tm.setChildren(childList);//给根节点设置子节点
        }
        return rootMenu;
    }

    /**
     * 获取子节点
     * @param id 父节点id
     * @param allMenu 所有菜单列表
     * @return 每个根节点下，所有子菜单列表
     */
    public List<AllType> getChild(String id, List<AllType> allMenu){
        //子菜单
        List<AllType> childList = new ArrayList<>();
        for (AllType tm : allMenu) {
            // 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
            //相等说明：为该根节点的子节点。
            if(tm.getParentId().equals(id)){
                childList.add(tm);
            }
        }
        //递归
        for (AllType nav : childList) {
            nav.setChildren(getChild(nav.getId(), allMenu));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if(childList.size() == 0){
//            return new ArrayList<>();
            return null;
        }
        return childList;
    }
}
